package RoomManagement

import (
	"MedicalTreatment/global"
	"MedicalTreatment/model"
	"fmt"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"strconv"
	"time"
)

type Upload struct {
	ResultId int
	RoomId   int
	BedId    int
}

func InpatientAdd(r *gin.Engine) {
	r.POST("/InpatientAdd", func(context *gin.Context) {
		var upload Upload
		if err := context.ShouldBindJSON(&upload); err != nil {
			context.JSON(200, gin.H{
				"Msg": err,
			})
			return
		}
		var results model.Result
		if err := global.DB.Table("results").Where("id = ?", upload.ResultId).First(&results).Error; err != nil {
			context.JSON(200, gin.H{
				"Msg": err,
			})
			return
		}
		times, err := strconv.Atoi(results.HospitalStay)
		if err != nil {
			fmt.Println("转换失败", err)
		}
		endtimeDate := time.Now().AddDate(0, 0, times)
		endtimeStr := endtimeDate.Format("2006-01-02 15:04:05")
		inpatientInquiry := model.InpatientInquiry{
			Model:     gorm.Model{},
			PatId:     results.PatientId,
			PatName:   results.PatientName,
			PatAge:    results.PatientAge,
			Diagnosis: results.Diagnosis,
			RoomId:    upload.RoomId,
			StartTime: time.Now().Format("2006-01-02 15:04:05"),
			EndTime:   endtimeStr,
		}
		if err := global.DB.Create(&inpatientInquiry).Error; err != nil {
			context.JSON(200, gin.H{
				"Msg": err,
			})
			return
		} else {
			if err := global.DB.Model(&model.Bed{}).Where("id = ?", upload.BedId).Updates(model.Bed{PatientName: results.PatientName, PatientId: results.PatientId}).Error; err != nil {
				context.JSON(200, gin.H{
					"Msg": err,
				})
				return
			}
			context.JSON(200, gin.H{
				"Msg": "创建成功",
			})
		}

	})
}
